package ffmpeg;

import com.alibaba.fastjson.JSONObject;
import enums.FFmpegCodeEnum;
import exception.FFmpegException;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

public class FFprobe {

    private String address;

    private String ffprobePath;

    private long timeMillis;

    private String vcodec;

    public FFprobe(String ffprobePath, String address, long timeMillis) {
        this.ffprobePath = ffprobePath;
        this.address = address;
        this.timeMillis = timeMillis;
    }

    public void isNormal() {
        try {
            String command = executeCommand();
            if (!StringUtils.isBlank(command) || command.equals("{\n")) {
                JSONObject jsonObject = JSONObject.parseObject(command);
                List<JSONObject> streams = jsonObject.getJSONArray("streams").toJavaList(JSONObject.class);
                if (streams.size() > 0) {
                    for (JSONObject stream : streams) {
                        if ("video".equals(stream.getString("codec_type"))) {
                            vcodec = stream.getString("codec_name");
                            break;
                        }
                    }
                }
            } else {
                throw  new FFmpegException(FFmpegCodeEnum.FFPROBE_ERROR);
            }
        } catch (IOException e) {
            throw new FFmpegException(FFmpegCodeEnum.FFPROBE_NONE);
        }
    }

    private String executeCommand() throws IOException {

        ProcessBuilder builder = new ProcessBuilder(Args.camera_probe(ffprobePath, address));
        builder.redirectErrorStream(true);
        Process process = builder.start();

        process.getOutputStream().close();

        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        long start = System.currentTimeMillis();
        new Thread(() -> {
            while (true) {
                if (System.currentTimeMillis() - start > timeMillis) {
                    process.destroy();
                    return;
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        while (StringUtils.isNotEmpty(line = reader.readLine())) {
            stringBuilder.append(line).append("\n");
        }
        return stringBuilder.toString();
    }

    public String getVcodec() {
        return vcodec;
    }
}
